#! /usr/bin/python
#
# xpl-nut
# V.1.0 (oct. 2011)
# xPL client for NUT daemon
# Copyright (C) 2011  GuiguiAbloc
# http://blog.guiguiabloc.fr
#
# Based on Python toolkit from John Bent
# Copyright (C) 2004 by John Bent
# http://www.xplproject.org.uk/

import socket, sys, string 
import sched, time 

#############
# variables
#############
upsaddr='192.168.0.10' 
upsport=3493
polltime=10 
nomups = 'mgeups'

xpladdr = ("255.255.255.255",3865)
xplport = 3865
UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)

def SendHeartbeat() :
  msg = "xpl-stat\n{\nhop=1\nsource=guiguiabl-xpl.python\ntarget=*\n}\nhbeat.app\n{\ninterval=5\nport=" + str(xplport) + "\n}\n"
  UDPSock.sendto(msg,("255.255.255.255",3865))
SendHeartbeat()


#############
# PROGRAMME #
#############
hostname = socket.gethostname()

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

# definition du temps de Polling
temps = sched.scheduler(time.time, time.sleep)
 
#creation de la socket puis connexion
s       = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((upsaddr,upsport))
except Exception, e:
    alert('Une erreur est survenue avec %s:%d. Exception type est %s' % (upsaddr, upsport, `e`))
 
# preparation de la requete
etatonduleur = "get var "+nomups+" ups.status\r\n"
voltage= "get var "+nomups+" input.voltage\r\n"
batterycharge= "get var "+nomups+" battery.charge\r\n"

 
# envoi puis reception de la reponse toutes les x polltime
def poll_ups(tc):

    s.send(etatonduleur)
    data = s.recv(50)
    resultat = data.split()
    statusbatt = resultat.pop()
    statusbatt = statusbatt.replace('"','')
    statusbatt = statusbatt.replace('OL','onmains')
    statusbatt = statusbatt.replace('OB','onbattery')
    statusbatt = statusbatt.replace('LB','lowbattery')
    body = 'status=battery\nevent='+statusbatt
    msg = "xpl-trig\n{\nhop=1\nsource=guigui-xplnut."+hostname+"\ntarget=*\n}\nups.basic\n{\n" + body + "\n}\n"
    UDPSock.sendto(msg,xpladdr)
    print msg

    s.send(voltage)
    voltageresult = s.recv(50)
    resultatvolt = voltageresult.split()
    voltagein = resultatvolt.pop()
    voltagein = voltagein.replace('"','')
    body = 'device='+nomups+'\ntype=voltage\ncurrent='+voltagein
    msg = "xpl-trig\n{\nhop=1\nsource=guigui-xplnut."+hostname+"\ntarget=*\n}\nsensor.basic\n{\n" + body + "\n}\n"
    UDPSock.sendto(msg,xpladdr)
    print msg

    s.send(batterycharge)
    batterychargeresult = s.recv(50)
    resultatbatt = batterychargeresult.split()
    chargebatt = resultatbatt.pop()
    chargebatt = chargebatt.replace('"','')
    body = 'device='+nomups+'\ntype=battery\ncurrent='+chargebatt
    msg = "xpl-trig\n{\nhop=1\nsource=guigui-xplnut."+hostname+"\ntarget=*\n}\nsensor.basic\n{\n" + body + "\n}\n"
    UDPSock.sendto(msg,xpladdr)
    print msg


    tc.enter(polltime, 1, poll_ups, (tc,))

temps.enter(polltime, 1, poll_ups, (temps,))
temps.run()

